﻿using WinformDevelopFrame.Entity;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.IO;
using System.Linq;
using SqlSugar;
using WinformDevelopFrame.IServices;
using DevExpress.XtraEditors.Controls;
using DevExpress.XtraEditors;
using System.Windows.Forms;
using WinformDevelopFrame.Core.Extend;
using DevExpress.Utils.Win;
using DevExpress.Xpo.DB.Helpers;
using DevExpress.XtraGrid;
using WinformDevelopFrame.Template;
using System.Runtime.Intrinsics.Arm;
using System.Security.Principal;
using System.IO.Ports;
using DevExpress.XtraTab;
using SqlSugar.IOC;
using DbType = SqlSugar.DbType;

namespace WinformDevelopFrame.UI
{
    public partial class FrmGeneratedCode : DevExpress.XtraEditors.XtraForm
    {
        private string directoryPath= AppDomain.CurrentDomain.BaseDirectory + @"\Layout\";
        private string gridLayout_frmGeneratedCode = AppDomain.CurrentDomain.BaseDirectory + @"\Layout\gridLayout_frmGeneratedCode.xml";
        private IsysconnectService _sysConnectService;
        private ISqlSugarClient _sqlSugarClient;
        private ISysDataTableService _sysDataTableService;
        private ISqlSugarClient db;
        private bool IsMuSelect = true;
        public FrmGeneratedCode(IsysconnectService sysConnectService, ISqlSugarClient sqlSugarClient, ISysDataTableService sysDataTableService)
        {
            _sysConnectService = sysConnectService;
            _sqlSugarClient = sqlSugarClient;
            InitializeComponent();
            _sysDataTableService = sysDataTableService;
        }

        private void FrmGeneratedCode_Load(object sender, EventArgs e)
        {
            comboBoxEdit8.Properties.Items.AddRange(_sysConnectService.Query().Select(p => p.ConnectName).ToList());
            GridGroupSummaryItem item = new GridGroupSummaryItem();
            item.FieldName = "TableName";
            gridView1.GroupSummary.Add(item);
            gridControl1.ForceInitialize();
            // Restore the previously saved layout 
            if(File.Exists(gridLayout_frmGeneratedCode))
                gridControl1.MainView.RestoreLayoutFromXml(gridLayout_frmGeneratedCode);
            repositoryItemComboBox3.Items.AddRange(_sysDataTableService.Query().Select(p=>p.DataTableName).ToList());
        }

        private void comboBoxEdit8_SelectedIndexChanged(object sender, EventArgs e)
        {
            var sysConnect = _sysConnectService.QueryByClause(p => p.ConnectName.Equals(comboBoxEdit8.Text));
            textEdit1.Text = _sqlSugarClient.Queryable<sysdicdata>().First(p=>p.Id== sysConnect.DbType).DicData ;
            textEdit2.Text = sysConnect?.ConnectStr;
            textEdit3.Text = sysConnect?.DbName;
            var dbname = sysConnect.DbName;
            //
            db = new SqlSugarClient(new ConnectionConfig
            {
                ConnectionString = textEdit2.Text, // 设置数据库连接字符串
                DbType = textEdit1.Text == IocDbType.MySql.ToString()
                    ? DbType.MySql
                    : DbType.SqlServer,
                IsAutoCloseConnection = true,
                InitKeyType = InitKeyType.Attribute // 如果使用实体类的属性进行主键标识，请设置为 InitKeyType.Attribute
            });
            var tablelist = db.Ado
                .SqlQuery<string>(
                    $"SELECT table_name FROM  information_schema.tables WHERE table_schema='{dbname}';").ToArray();
            checkedComboBoxEdit1.Properties.Items.AddRange(tablelist);
            comboBoxEdit2.Properties.Items.AddRange(tablelist);
            comboBoxEdit4.Properties.Items.AddRange(tablelist);
            comboBoxEdit6.Properties.Items.AddRange(tablelist);
            comboBoxEdit1.Properties.Items.AddRange(GetTableFieldName(comboBoxEdit8.Text));
            comboBoxEdit9.Properties.Items.AddRange(GetTableFieldName(comboBoxEdit8.Text));
            comboBoxEdit10.Properties.Items.AddRange(GetTableFieldName(comboBoxEdit8.Text));

        }


        private void checkEdit2_Click(object sender, EventArgs e)
        {
            checkEdit3.Checked = false;
            checkEdit4.Checked = false;
            checkEdit1.Checked = false;

        }

        private void checkEdit3_Click(object sender, EventArgs e)
        {
            checkEdit2.Checked = false;
            checkEdit4.Checked = false;
            checkEdit1.Checked = false;
        }

        private void checkEdit1_Click(object sender, EventArgs e)
        {
            checkEdit3.Checked = false;
            checkEdit4.Checked = false;
            checkEdit2.Checked = false;
        }

        private void checkEdit4_Click(object sender, EventArgs e)
        {
            checkEdit3.Checked = false;
            checkEdit2.Checked = false;
            checkEdit1.Checked = false;
        }

        private void Set1()
        {
            if (checkEdit2.Checked)
            {
                comboBoxEdit2.ReadOnly = true;
                comboBoxEdit3.ReadOnly = true;
                comboBoxEdit4.ReadOnly = true;
                comboBoxEdit5.ReadOnly = true;
                comboBoxEdit6.ReadOnly = true;
                comboBoxEdit7.ReadOnly = true;
                comboBoxEdit1.ReadOnly = true;
                comboBoxEdit9.ReadOnly = true;
                comboBoxEdit10.ReadOnly = true;
                IsMuSelect = true;
                //checkedComboBoxEdit1.Properties.
            }
            if (checkEdit3.Checked)
            {
                comboBoxEdit2.ReadOnly = false;
                comboBoxEdit3.ReadOnly = false;
                comboBoxEdit4.ReadOnly = true;
                comboBoxEdit5.ReadOnly = true;
                comboBoxEdit6.ReadOnly = true;
                comboBoxEdit7.ReadOnly = true;
                comboBoxEdit1.ReadOnly = false;
                comboBoxEdit9.ReadOnly = true;
                comboBoxEdit10.ReadOnly = true;
                IsMuSelect = false;
            }
            if (checkEdit1.Checked)
            {
                comboBoxEdit2.ReadOnly = false;
                comboBoxEdit3.ReadOnly = false;
                comboBoxEdit4.ReadOnly = false;
                comboBoxEdit5.ReadOnly = false;
                comboBoxEdit6.ReadOnly = true;
                comboBoxEdit7.ReadOnly = true;
                comboBoxEdit1.ReadOnly = false;
                comboBoxEdit9.ReadOnly = false;
                comboBoxEdit10.ReadOnly = true;
                IsMuSelect = false;
            }
            if (checkEdit4.Checked)
            {
                comboBoxEdit2.ReadOnly = false;
                comboBoxEdit3.ReadOnly = false;
                comboBoxEdit4.ReadOnly = false;
                comboBoxEdit5.ReadOnly = false;
                comboBoxEdit6.ReadOnly = false;
                comboBoxEdit7.ReadOnly = false;
                comboBoxEdit1.ReadOnly = false;
                comboBoxEdit9.ReadOnly = false;
                comboBoxEdit10.ReadOnly = false;
                IsMuSelect = false;
            }
        }

        private void checkEdit2_CheckedChanged(object sender, EventArgs e)
        {
            Set1();
        }

        private void checkEdit3_CheckedChanged(object sender, EventArgs e)
        {
            Set1();
        }

        private void checkEdit1_CheckedChanged(object sender, EventArgs e)
        {
            Set1();
        }

        private void checkEdit4_CheckedChanged(object sender, EventArgs e)
        {
            Set1();
        }

        private void comboBoxEdit2_SelectedIndexChanged(object sender, EventArgs e)
        {
            comboBoxEdit3.Properties.Items.AddRange(GetTableFieldName(comboBoxEdit2.Text));
        }

        private void comboBoxEdit4_SelectedIndexChanged(object sender, EventArgs e)
        {
            comboBoxEdit5.Properties.Items.AddRange(GetTableFieldName(comboBoxEdit4.Text));

        }

        private void comboBoxEdit6_SelectedIndexChanged(object sender, EventArgs e)
        {
            comboBoxEdit7.Properties.Items.AddRange(GetTableFieldName(comboBoxEdit6.Text));
        }

        private List<string> GetTableFieldName(string tableName)
        {
            string sql = $"select COLUMN_NAME from information_schema.COLUMNS where table_name = '{tableName}' and table_schema ='winformdevelopframe'";
            List<string> result = new List<string>();
            result = db.Ado
                .SqlQuery<string>(sql);
            return result;
        }

        private void checkedComboBoxEdit1_EditValueChanged(object sender, EventArgs e)
        {
            if(db!=null)
                Check();
        }

        private void Check()
        {
            if (checkEdit1.Checked || checkEdit3.Checked || checkEdit4.Checked)
            {
                if (checkedComboBoxEdit1.Text.Split(",").Length > 1)
                {
                    "非单表模式只能选择一张数据表".ShowTips();
                    checkedComboBoxEdit1.Text = checkedComboBoxEdit1.Text.Split(",")[0];
                }
            }
            gridControl1.DataSource = GetTableInfo(checkedComboBoxEdit1.Text.Split(", ").ToList());
        }

        private List<TableInfo> GetTableInfo(List<string> tableNames)
        {
            List<TableInfo> result = new List<TableInfo>();

            tableNames.ForEach(p =>
            {
                string sql = $"select table_name TableName,COLUMN_name ColumnName,data_type DataType,column_comment  Remark,extra ,COLUMN_KEY from information_schema.columns where TABLE_NAME='{p}' and table_schema ='winformdevelopframe' ORDER BY ordinal_position";
                result.AddRange(db.Ado
                    .SqlQuery<TableInfo>(sql));
            });
            int num = 1;
            result.ForEach(p =>
            {
                p.LabelText = p.Remark+":";
                p.ControlName = p.ColumnName;
                p.LabelName = "lbl"+p.ColumnName;
                p.No = num;
                p.FieldType = GetClassFiledType(p.DataType);
                p.ControlType = "TextEdit";
                num++;
            });
            return result;
        }
        private void checkEdit1_EditValueChanged(object sender, EventArgs e)
        {
            Check();
        }

        private void checkEdit3_EditValueChanged(object sender, EventArgs e)
        {
            Check();
        }

        private void checkEdit4_EditValueChanged(object sender, EventArgs e)
        {
            Check();
        }

        private void simpleButton2_Click(object sender, EventArgs e)
        {
            if (CheckData())
            {
                var data = (List<TableInfo>)gridControl1.DataSource;
                WinformAdapter winform = new WinformAdapter();
                ServiceRepositoryCreate serviceRepositoryCreate = new ServiceRepositoryCreate();
                EntityCreate entityCreate = new EntityCreate();
                var dic = data.GroupBy(p => p.TableName);
                try
                {
                    foreach (var item in dic)
                    {
                        if (checkEdit6.Checked)
                        {
                            entityCreate.Create(item.Key, textEdit4.Text, textEdit5.Text, item.OrderBy(p=>p.No).ToList());
                        }
                        if (checkEdit5.Checked)
                        {
                            serviceRepositoryCreate.Create(item.Key, textEdit4.Text, textEdit5.Text);
                        }
                        if (checkEdit7.Checked)
                        {
                            winform.create(item.Key, textEdit4.Text, textEdit5.Text, item.OrderBy(p => p.No).ToList(), int.Parse(textEdit6.Text));
                        }
                    }
                    "生成成功！".ShowTips();
                }
                catch (Exception ex)
                {
                    ex.StackTrace.ShowError();
                }

            }

        }

        private bool CheckData()
        {
            if (string.IsNullOrEmpty(checkedComboBoxEdit1.Text))
            {
                "请选择数据表".ShowTips();
                return false;
            }
            if (string.IsNullOrEmpty(textEdit4.Text))
            {
                "请填写命名空间".ShowTips();
                return false;
            }
            if (string.IsNullOrEmpty(textEdit5.Text))
            {
                "请选择输出目录".ShowTips();
                return false;
            }
            return true;
        }
        private void simpleButton1_Click(object sender, EventArgs e)
        {
            if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
            {
                textEdit5.Text = folderBrowserDialog1.SelectedPath;
            }
        }

        private string GetClassFiledType(string type)
        {
            switch (type)
            {
                case "varchar": return "string";
                case "int": return "int";
                case "bit": return "bool";
                case "datetime": return "DateTime";
                case "decimal": return "decimal";
            }
            return "object";
        }

        private void FrmGeneratedCode_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (!Directory.Exists(directoryPath))  
            {
                Directory.CreateDirectory(directoryPath);
            }
            if (!File.Exists(gridLayout_frmGeneratedCode))
            {
                File.Create(gridLayout_frmGeneratedCode).Close();
            }
            
            gridControl1.MainView.SaveLayoutToXml(gridLayout_frmGeneratedCode);
        }

        private void simpleButton3_Click(object sender, EventArgs e)
        {
            var p = (XtraTabPage)this.Parent;
            if (p != null)
            {
                var tab = (XtraTabControl)p.Parent;
                tab.TabPages.Remove(p);
                tab.SelectedTabPageIndex = tab.TabPages.Count - 1;
            }
            this.Close();
        }
    }
}